package com.itheima.interceptor;

import com.itheima.util.JwtUtils;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

@Component
@Slf4j
public class TokenInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
//        //1: 获取请求路径
//        String url = request.getRequestURL().toString();
//
//        //2:判断请求url中是否包含login
//        if(url.contains("login")){
//            //3:如果包含login,放行
//            log.info("登录请求,放行");
//            return true;
//        }
        //3: 从请求头中获取令牌
        String token = request.getHeader("token");
        //4: 判断令牌是否为空,为空拦截
        if(token==null||token.length()==0){
            log.info("请求头中无token,返回错误信息");
            response.setStatus(401);
            return false;
        }
        //5:解析令牌
        try {
            JwtUtils.parseJWT(token);
        }catch (Exception e){
            log.info("令牌解析失败,返回错误信息");
            response.setStatus(401);
            return false;
        }
        //6:放行
        log.info("令牌合法,放行");
        return true;
    }
}
